﻿var app = angular.module("app", ["xeditable"]);
app.run(function (editableOptions) {
    editableOptions.theme = 'bs3'; // bootstrap3 theme. Can be also 'bs2', 'default'
});

app.controller('EditableRowCtrl', function ($scope, $filter, $http) {
    $('#ajax_loader').show();

    $http.get('/api/locationapi/get').success(function (data) {
        $scope.locations = data;
        if (data.length > 0) {
            $scope.myLocation = data[0];
            $http.get('/api/districtapi/GetDistrictsByLocationId?locationId=' + $scope.myLocation.id).success(function (districts) {
                $scope.districts = districts;
                $('#ajax_loader').hide();
            })
            .error(function () {
                $('#ajax_loader').hide();
            });
        }
        $('#ajax_loader').hide();
    });

    $scope.locationChanged = function (parameters) {
        $('#ajax_loader').show();
        $http.get('/api/districtapi/GetDistrictsByLocationId?locationId=' + $scope.myLocation.id).success(function (districts) {
            $scope.districts = districts;
            $('#ajax_loader').hide();
        })
        .error(function () {
            $('#ajax_loader').hide();
        });
    };

    $scope.saveDistrict = function (data, id) {
        //$scope.District not updated yet
        if (id) {
            angular.extend(data, { id: id, locationId: $scope.myLocation.id });
            return $http.post('/api/districtapi/update', data);
        } else {
            angular.extend(data, { locationId: $scope.myLocation.id });
            return $http.post('/api/districtapi/add', data).success(function (data) {
                $scope.districts[$scope.districts.length - 1].id = data.id;
            });
        }
    };

    // remove District
    $scope.removeDistrict = function (index) {
        var delDistrict = $scope.districts[index];
        $('#myModal-' + index).modal('toggle');
        $('.modal-backdrop').remove();
        return $http.post('/api/districtapi/remove', delDistrict).success(function () {
            $scope.districts.splice(index, 1);
        });
    };

    // add District
    $scope.addDistrict = function () {
        $scope.inserted = {
            id: '',
            name: '',
            locationId: $scope.myLocation.id
        };
        $scope.districts.push($scope.inserted);
    };
});